/**
 * 社区功能API路由
 */
import express, { type Request, type Response } from 'express';

const router = express.Router();

// 帖子接口类型定义
interface Post {
  id: string;
  userId: string;
  author: {
    id: string;
    name: string;
    avatar: string;
    level?: number;
    isVerified?: boolean;
  };
  title?: string;
  content: string;
  type: 'text' | 'image' | 'video';
  images?: string[];
  video?: {
    url: string;
    cover: string;
    duration: number;
  };
  topics?: Topic[];
  location?: {
    name: string;
    latitude?: number;
    longitude?: number;
  };
  likeCount: number;
  commentCount: number;
  shareCount: number;
  viewCount: number;
  isLiked?: boolean;
  isCollected?: boolean;
  allowComment: boolean;
  isPublic: boolean;
  createdAt: string;
  updatedAt: string;
}

interface Topic {
  id: string;
  name: string;
  description?: string;
  postCount: number;
  followCount: number;
  isFollowing?: boolean;
  cover?: string;
  isHot?: boolean;
  createdAt: string;
}

interface Comment {
  id: string;
  postId: string;
  userId: string;
  author: {
    id: string;
    name: string;
    avatar: string;
  };
  content: string;
  images?: string[];
  parentId?: string;
  replyToUserId?: string;
  replyToUserName?: string;
  likeCount: number;
  isLiked?: boolean;
  replies?: Comment[];
  createdAt: string;
}

// 模拟数据存储
let posts: Post[] = [
  {
    id: '1',
    userId: 'user1',
    author: {
      id: 'user1',
      name: '新手妈妈小李',
      avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=young%20mother%20portrait%20smiling&image_size=square',
      level: 3,
      isVerified: true
    },
    title: '宝宝第一次翻身成功！',
    content: '今天宝宝终于学会翻身了，好激动！分享一下这个里程碑时刻 #宝宝成长 #新手妈妈',
    type: 'image',
    images: [
      'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20rolling%20over%20milestone%20cute&image_size=landscape_4_3',
      'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=happy%20baby%20lying%20on%20blanket&image_size=landscape_4_3'
    ],
    topics: [
      { id: 'topic1', name: '宝宝成长', description: '记录宝宝成长的每一个瞬间', postCount: 1250, followCount: 3200, isHot: true, createdAt: '2024-01-01T00:00:00Z' },
      { id: 'topic2', name: '新手妈妈', description: '新手妈妈交流经验', postCount: 890, followCount: 2100, createdAt: '2024-01-01T00:00:00Z' }
    ],
    likeCount: 156,
    commentCount: 23,
    shareCount: 12,
    viewCount: 890,
    allowComment: true,
    isPublic: true,
    createdAt: '2024-01-20T10:30:00Z',
    updatedAt: '2024-01-20T10:30:00Z'
  },
  {
    id: '2',
    userId: 'user2',
    author: {
      id: 'user2',
      name: '育儿专家王医生',
      avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20pediatrician%20doctor%20portrait&image_size=square',
      level: 8,
      isVerified: true
    },
    content: '关于宝宝辅食添加的几个重要时间点，新手父母一定要知道！\n\n1. 6个月开始添加辅食\n2. 先从单一食材开始\n3. 观察过敏反应\n4. 逐步增加食材种类\n\n有问题可以随时咨询哦～',
    type: 'text',
    topics: [
      { id: 'topic3', name: '辅食添加', description: '宝宝辅食添加指南', postCount: 567, followCount: 1800, createdAt: '2024-01-01T00:00:00Z' },
      { id: 'topic4', name: '专家建议', description: '专业育儿建议', postCount: 234, followCount: 5600, isHot: true, createdAt: '2024-01-01T00:00:00Z' }
    ],
    likeCount: 289,
    commentCount: 45,
    shareCount: 67,
    viewCount: 1520,
    allowComment: true,
    isPublic: true,
    createdAt: '2024-01-19T14:20:00Z',
    updatedAt: '2024-01-19T14:20:00Z'
  }
];

let topics: Topic[] = [
  { id: 'topic1', name: '宝宝成长', description: '记录宝宝成长的每一个瞬间', postCount: 1250, followCount: 3200, isHot: true, createdAt: '2024-01-01T00:00:00Z' },
  { id: 'topic2', name: '新手妈妈', description: '新手妈妈交流经验', postCount: 890, followCount: 2100, createdAt: '2024-01-01T00:00:00Z' },
  { id: 'topic3', name: '辅食添加', description: '宝宝辅食添加指南', postCount: 567, followCount: 1800, createdAt: '2024-01-01T00:00:00Z' },
  { id: 'topic4', name: '专家建议', description: '专业育儿建议', postCount: 234, followCount: 5600, isHot: true, createdAt: '2024-01-01T00:00:00Z' },
  { id: 'topic5', name: '睡眠训练', description: '宝宝睡眠问题解决方案', postCount: 445, followCount: 1200, createdAt: '2024-01-01T00:00:00Z' }
];

let comments: Comment[] = [
  {
    id: 'comment1',
    postId: '1',
    userId: 'user3',
    author: {
      id: 'user3',
      name: '宝妈小张',
      avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=mother%20portrait%20friendly&image_size=square'
    },
    content: '恭喜恭喜！我家宝宝也是这个月龄学会翻身的，真的很激动呢！',
    likeCount: 12,
    createdAt: '2024-01-20T11:00:00Z'
  },
  {
    id: 'comment2',
    postId: '1',
    userId: 'user4',
    author: {
      id: 'user4',
      name: '奶爸阿强',
      avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=father%20portrait%20caring&image_size=square'
    },
    content: '太棒了！记得要给宝宝更多练习的机会哦',
    likeCount: 8,
    createdAt: '2024-01-20T11:15:00Z'
  }
];

/**
 * 获取帖子列表
 * GET /api/community/posts
 */
router.get('/posts', (req: Request, res: Response) => {
  try {
    const {
      page = 1,
      limit = 10,
      type,
      topicId,
      userId,
      sortBy = 'latest'
    } = req.query;
    
    let filteredPosts = [...posts];
    
    // 按类型筛选
    if (type) {
      filteredPosts = filteredPosts.filter(post => post.type === type);
    }
    
    // 按话题筛选
    if (topicId) {
      filteredPosts = filteredPosts.filter(post => 
        post.topics?.some(topic => topic.id === topicId)
      );
    }
    
    // 按用户筛选
    if (userId) {
      filteredPosts = filteredPosts.filter(post => post.userId === userId);
    }
    
    // 排序
    if (sortBy === 'hot') {
      filteredPosts.sort((a, b) => {
        const scoreA = a.likeCount * 2 + a.commentCount * 3 + a.shareCount * 5;
        const scoreB = b.likeCount * 2 + b.commentCount * 3 + b.shareCount * 5;
        return scoreB - scoreA;
      });
    } else if (sortBy === 'latest') {
      filteredPosts.sort((a, b) => 
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      );
    }
    
    // 分页
    const startIndex = (Number(page) - 1) * Number(limit);
    const endIndex = startIndex + Number(limit);
    const paginatedPosts = filteredPosts.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        list: paginatedPosts,
        total: filteredPosts.length,
        page: Number(page),
        limit: Number(limit),
        hasMore: endIndex < filteredPosts.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取帖子列表失败'
    });
  }
});

/**
 * 获取帖子详情
 * GET /api/community/posts/:id
 */
router.get('/posts/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const post = posts.find(p => p.id === id);
    
    if (!post) {
      return res.status(404).json({
        success: false,
        error: '帖子不存在'
      });
    }
    
    // 增加浏览量
    const postIndex = posts.findIndex(p => p.id === id);
    posts[postIndex].viewCount += 1;
    
    res.json({
      success: true,
      data: post
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取帖子详情失败'
    });
  }
});

/**
 * 发布帖子
 * POST /api/community/posts
 */
router.post('/posts', (req: Request, res: Response) => {
  try {
    const {
      userId,
      title,
      content,
      type = 'text',
      images,
      video,
      topics,
      location,
      allowComment = true,
      isPublic = true
    } = req.body;
    
    if (!userId || !content) {
      return res.status(400).json({
        success: false,
        error: '用户ID和内容为必填项'
      });
    }
    
    const newPost: Post = {
      id: Date.now().toString(),
      userId,
      author: {
        id: userId,
        name: '用户' + userId,
        avatar: `https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=user%20avatar%20${userId}&image_size=square`
      },
      title,
      content,
      type,
      images,
      video,
      topics: topics || [],
      location,
      likeCount: 0,
      commentCount: 0,
      shareCount: 0,
      viewCount: 0,
      allowComment,
      isPublic,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    
    posts.unshift(newPost);
    
    res.status(201).json({
      success: true,
      data: newPost
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '发布帖子失败'
    });
  }
});

/**
 * 点赞帖子
 * POST /api/community/posts/:id/like
 */
router.post('/posts/:id/like', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { userId, action = 'like' } = req.body;
    
    const postIndex = posts.findIndex(p => p.id === id);
    if (postIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '帖子不存在'
      });
    }
    
    if (action === 'like') {
      posts[postIndex].likeCount += 1;
      posts[postIndex].isLiked = true;
    } else {
      posts[postIndex].likeCount = Math.max(0, posts[postIndex].likeCount - 1);
      posts[postIndex].isLiked = false;
    }
    
    res.json({
      success: true,
      data: {
        likeCount: posts[postIndex].likeCount,
        isLiked: posts[postIndex].isLiked
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '操作失败'
    });
  }
});

/**
 * 获取帖子评论
 * GET /api/community/posts/:id/comments
 */
router.get('/posts/:id/comments', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { page = 1, limit = 20, sortBy = 'latest' } = req.query;
    
    let postComments = comments.filter(c => c.postId === id && !c.parentId);
    
    // 排序
    if (sortBy === 'hot') {
      postComments.sort((a, b) => b.likeCount - a.likeCount);
    } else {
      postComments.sort((a, b) => 
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      );
    }
    
    // 为每个评论添加回复
    postComments = postComments.map(comment => {
      const replies = comments.filter(c => c.parentId === comment.id);
      return { ...comment, replies };
    });
    
    // 分页
    const startIndex = (Number(page) - 1) * Number(limit);
    const endIndex = startIndex + Number(limit);
    const paginatedComments = postComments.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        list: paginatedComments,
        total: postComments.length,
        page: Number(page),
        limit: Number(limit),
        hasMore: endIndex < postComments.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取评论失败'
    });
  }
});

/**
 * 发表评论
 * POST /api/community/posts/:id/comments
 */
router.post('/posts/:id/comments', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { userId, content, images, parentId, replyToUserId } = req.body;
    
    if (!userId || !content) {
      return res.status(400).json({
        success: false,
        error: '用户ID和评论内容为必填项'
      });
    }
    
    const newComment: Comment = {
      id: Date.now().toString(),
      postId: id,
      userId,
      author: {
        id: userId,
        name: '用户' + userId,
        avatar: `https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=user%20avatar%20${userId}&image_size=square`
      },
      content,
      images,
      parentId,
      replyToUserId,
      likeCount: 0,
      createdAt: new Date().toISOString()
    };
    
    comments.push(newComment);
    
    // 更新帖子评论数
    const postIndex = posts.findIndex(p => p.id === id);
    if (postIndex !== -1) {
      posts[postIndex].commentCount += 1;
    }
    
    res.status(201).json({
      success: true,
      data: newComment
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '发表评论失败'
    });
  }
});

/**
 * 获取话题列表
 * GET /api/community/topics
 */
router.get('/topics', (req: Request, res: Response) => {
  try {
    const { page = 1, limit = 20, keyword, isHot } = req.query;
    
    let filteredTopics = [...topics];
    
    // 关键词搜索
    if (keyword) {
      const kw = (keyword as string).toLowerCase();
      filteredTopics = filteredTopics.filter(topic => 
        topic.name.toLowerCase().includes(kw) ||
        topic.description?.toLowerCase().includes(kw)
      );
    }
    
    // 热门话题筛选
    if (isHot === 'true') {
      filteredTopics = filteredTopics.filter(topic => topic.isHot);
    }
    
    // 按关注数排序
    filteredTopics.sort((a, b) => b.followCount - a.followCount);
    
    // 分页
    const startIndex = (Number(page) - 1) * Number(limit);
    const endIndex = startIndex + Number(limit);
    const paginatedTopics = filteredTopics.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        list: paginatedTopics,
        total: filteredTopics.length,
        page: Number(page),
        limit: Number(limit),
        hasMore: endIndex < filteredTopics.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取话题列表失败'
    });
  }
});

/**
 * 关注话题
 * POST /api/community/topics/:id/follow
 */
router.post('/topics/:id/follow', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { userId, action = 'follow' } = req.body;
    
    const topicIndex = topics.findIndex(t => t.id === id);
    if (topicIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '话题不存在'
      });
    }
    
    if (action === 'follow') {
      topics[topicIndex].followCount += 1;
      topics[topicIndex].isFollowing = true;
    } else {
      topics[topicIndex].followCount = Math.max(0, topics[topicIndex].followCount - 1);
      topics[topicIndex].isFollowing = false;
    }
    
    res.json({
      success: true,
      data: {
        followCount: topics[topicIndex].followCount,
        isFollowing: topics[topicIndex].isFollowing
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '操作失败'
    });
  }
});

/**
 * 删除帖子
 * DELETE /api/community/posts/:id
 */
router.delete('/posts/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { userId } = req.body;
    
    const postIndex = posts.findIndex(p => p.id === id);
    if (postIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '帖子不存在'
      });
    }
    
    // 检查权限（只能删除自己的帖子）
    if (posts[postIndex].userId !== userId) {
      return res.status(403).json({
        success: false,
        error: '无权限删除此帖子'
      });
    }
    
    posts.splice(postIndex, 1);
    
    // 删除相关评论
    comments = comments.filter(c => c.postId !== id);
    
    res.json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '删除帖子失败'
    });
  }
});

export default router;